package com.baidu.iit.pxp.el.juel;

import com.baidu.iit.pvm.ActivityException;
import com.baidu.iit.pvm.delegate.VariableScope;
import com.baidu.iit.pxp.PxpServiceManager;
import com.baidu.iit.pxp.delegate.Expression;
import com.baidu.iit.pxp.el.ELContext;
import com.baidu.iit.pxp.el.ELException;
import com.baidu.iit.pxp.el.ValueExpression;
import com.sun.javafx.fxml.PropertyNotFoundException;

/**
 * User: huangweili
 * Date: 14-4-29
 * Time: 下午3:01
 */
public class JuelExpression implements Expression {

    protected String expressionText;
    protected ValueExpression valueExpression;

    public JuelExpression(ValueExpression valueExpression, String expressionText) {
        this.valueExpression = valueExpression;
        this.expressionText = expressionText;
    }

    public Object getValue(VariableScope variableScope) {
        ELContext elContext = PxpServiceManager.getExpressionManager().getElContext(variableScope);
        try {
            ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext);

            return invocation.getInvocationResult();
        } catch (PropertyNotFoundException pnfe) {
            throw new ActivityException("Unknown property used in expression: " + expressionText, pnfe);
        } catch (MethodNotFoundException mnfe) {
            throw new ActivityException("Unknown method used in expression: " + expressionText, mnfe);
        } catch (ELException ele) {
            throw new ActivityException("Error while evaluating expression: " + expressionText, ele);
        } catch (Exception e) {
            throw new ActivityException("Error while evaluating expression: " + expressionText, e);
        }
    }

    public void setValue(Object value, VariableScope variableScope) {

        ELContext elContext = PxpServiceManager.getExpressionManager().getElContext(variableScope);
        try {
            ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value);

        } catch (Exception e) {
            throw new ActivityException("Error while evaluating expression: " + expressionText, e);
        }
    }

    @Override
    public String toString() {
        if (valueExpression != null) {
            return valueExpression.getExpressionString();
        }
        return super.toString();
    }

    public String getExpressionText() {
        return expressionText;
    }


}
